﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SPA_Prototype.Model;
using System.Diagnostics;
using System.Threading;

namespace SPA_Prototype
{
    public partial class Form1 : Form
    {
        static public USER_TYPE Privilege = USER_TYPE.NONE;

        InvoiceData[] _PrintArray;

        public Form1()
        {
            InitializeComponent();            
        }

        #region Check license
        private void Check_Lisence()
        {
            string key = "ZPYV-ERTY-4RTG-S345-RFVG-G65R";
                    //  StreamWriter rr = new StreamWriter(Application.StartupPath + "\\Licence.dat");
                     //  rr.WriteLine("0 " + DateTime.Now.ToString());
                     //  rr.Close();
            try
            {
                StreamReader sr = new StreamReader(Application.StartupPath + "\\Licence.dat");
                string temp = sr.ReadLine();
                sr.Close();
                if (temp != key)
                {
                    // set up for licence.dat
                    int index = temp.IndexOf(" ");
                    int day = 0;
                    int.TryParse(temp.Substring(0, index), out day);
                    DateTime date = DateTime.Now;
                    DateTime.TryParse(temp.Substring(index + 1), out date);

                    if (date.Day != DateTime.Now.Day) day++;
                    MessageBox.Show("You have 30 days trial !", "INFO - " + (30 - day).ToString() + " days left", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    if (day == 31)
                    {
                        MessageBox.Show("Out of 30 days trial", "WARN", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
                        Close();
                    }
                    else
                    {
                        StreamWriter sw = new StreamWriter(Application.StartupPath + "\\Licence.dat");
                        sw.WriteLine(day + " " + DateTime.Now.ToString());
                        sw.Close();
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        #endregion

        #region TabPage Control Method : Show/Hide
        // Hide 1 tabpage in Tabcontrol
        private void HideTabPage(TabPage tp, TabControl tabControl)
        {
            if (tabControl.TabPages.Contains(tp))
                tabControl.TabPages.Remove(tp);
        }

        // Show 1 tabpage in Tabcontrol
        private void ShowTabPage(TabPage tp, TabControl tabControl)
        {
            // first, remove all tabpages of this tabcontrol
            // then, add the tabpage we want to show
            int temp = tabControl1.TabCount;
            for (int j = 0; j < temp; j++)
                try
                {
                    tabControl1.TabPages.RemoveAt(0);
                }
                catch (Exception)
                {
                    MessageBox.Show("ex");
                    j--;
                }

            ShowTabPage(tp, tabControl, tabControl.TabPages.Count);
        }

        // this method: to add a new tabpage with its index
        private void ShowTabPage(TabPage tp, TabControl tabControl, int index)
        {
            if (tabControl.TabPages.Contains(tp)) return;
            InsertTabPage(tp, tabControl, index);
        }

        // this method: to insert a tabpage into tabcontrol 
        private void InsertTabPage(TabPage tabpage, TabControl tabControl, int index)
        {
            if (index < 0 || index > tabControl.TabCount)
                throw new ArgumentException("Index out of Range.");
            tabControl.TabPages.Add(tabpage);
            if (index < tabControl1.TabCount - 1)
                do
                {
                    SwapTabPages(tabpage, (tabControl.TabPages[tabControl.TabPages.IndexOf(tabpage) - 1]));
                }
                while (tabControl1.TabPages.IndexOf(tabpage) != index);
            tabControl1.SelectedTab = tabpage;
        }

        // swap position of 2 tabpages in tabcontrol
        private void SwapTabPages(TabPage tp1, TabPage tp2)
        {
            if (tabControl1.TabPages.Contains(tp1) == false || tabControl1.TabPages.Contains(tp2) == false)
                throw new ArgumentException("TabPages must be in the TabControls TabPageCollection.");

            int Index1 = tabControl1.TabPages.IndexOf(tp1);
            int Index2 = tabControl1.TabPages.IndexOf(tp2);
            tabControl1.TabPages[Index1] = tp2;
            tabControl1.TabPages[Index2] = tp1;
        }
        #endregion

        #region delegate/event/static function
       // public delegate void SendingEmailStatus(string s);
        public void SendingEmailStatus(string s)
        {
            LbStatus.Text = s;
        }
        
        #endregion

        VIPManagement VIPM;
        CustomerManagement CusM;
        CurrencyManagement CurM;
        PromotionManagement ProM;
        RoomManagement RooM;
        ServiceManagement SerM;
        PersonelManagement PerM;
        BillManagement BilM;
        History history;
        Export2Excel exp2Excel;


        // private variables
        SEARCH_METHOD SearchMethod = SEARCH_METHOD.ALL;
        TIME_CONSTRAIN SearchTime = TIME_CONSTRAIN.TODAY;
        string SearchKey = "";

        private void Form1_Load(object sender, EventArgs e)
        {
            // check license
            Check_Lisence();


            exp2Excel = new Export2Excel();
            InitPrintArray();
            VIPM = new VIPManagement(databaseDataSet);
            CusM = new CustomerManagement(databaseDataSet);
            CurM = new CurrencyManagement(databaseDataSet);
            ProM = new PromotionManagement(databaseDataSet);
            RooM = new RoomManagement(databaseDataSet);
            SerM = new ServiceManagement(databaseDataSet);
            PerM = new PersonelManagement(databaseDataSet);
            BilM = new BillManagement(databaseDataSet);
            history = new History();
            ShowTabPage(TabBill, tabControl1); 

            //add more Informations for CurM Class
            CusM.VIPLevel_Account = VIPM.MinAccount;
            CusM.VIPLevel_Point = VIPM.MinVisitTimes;

            // init for tab service
            TxtSM_VIPDiscount.Text = ProM.VIPDiscount.ToString(); //databaseDataSet.PromotionTable[0].VIPDiscount.ToString();
            TxtSM_VIPRoomCharge.Text = ProM.VIPRoomCharge.ToString(); //databaseDataSet.PromotionTable[0].VIPRoomCharge.ToString();
            TxtSM_VND.Text = CurM.ExchangeRate.ToString();
            
            // init for tab personel       
     
            // init for tab Bill
            ClearTextInTabBill();
            TxtBill_BillNo.Text = BilM.Current_BillNumber;
            PbBM_Save.Enabled = false;
                //-- customer
            CbBill_CustomerName.AutoCompleteCustomSource = CusM.GetSourceForKey(CUSTOMER_SERACH_METHOD.NAME);
            TxtBill_CustomerID.AutoCompleteCustomSource = CusM.GetSourceForKey(CUSTOMER_SERACH_METHOD.ID);
            TxtBill_Phone.AutoCompleteCustomSource = CusM.GetSourceForKey(CUSTOMER_SERACH_METHOD.PHONE);
            TxtBill_LV.AutoCompleteCustomSource = CusM.GetSourceForKey(CUSTOMER_SERACH_METHOD.LV);
            for (int j = 0; j < CbBill_CustomerName.AutoCompleteCustomSource.Count; j++) CbBill_CustomerName.Items.Add(CbBill_CustomerName.AutoCompleteCustomSource[j]);
                
                //--service
            CbBill_ServiceName.AutoCompleteCustomSource = SerM.GetSourceForService(SERVICE_SOURCE_TYPE.NAME);
            TxtBill_ServiceID.AutoCompleteCustomSource = SerM.GetSourceForService(SERVICE_SOURCE_TYPE.ID);
            for (int j = 0; j < CbBill_ServiceName.AutoCompleteCustomSource.Count; j++) CbBill_ServiceName.Items.Add(CbBill_ServiceName.AutoCompleteCustomSource[j]);
     
            // backup database if ...
            BackupManagement bacM = new BackupManagement(databaseDataSet);
            if (bacM.Auto == true)
            {
                string temp1 = string.Format("{0:M/d/yyyy}", DateTime.Now);
                if (temp1 != bacM.Date) bacM.Interval++;
                if (bacM.Interval >= bacM.Period)
                {
                    bacM.Interval = 0;

                    // backup data at local folder
                    string path = Application.StartupPath;
                    string source ="\"" + path + @"\Database.sdf" + "\"";
                    string seq = DateTime.Now.Month.ToString() + "_" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Year.ToString();
                    string destination = "";
                    string destinationForEmail = "";

                    ProcessStartInfo startInfo = new ProcessStartInfo(path + @"\WinRAR.exe");
                    startInfo.WindowStyle = ProcessWindowStyle.Maximized;
                    for (int j = 0; j < 2; j++)
                    {
                        if (j == 0)
                        {
                            if (bacM.Folder == "") continue;
                            destination = "\"" + @bacM.Folder + @"\Database_" + seq + ".rar\" ";       // user-defined
                        }
                        else
                        {
                            destination = "\"" + path + @"\Backup\Database_" + seq + ".rar\" ";  // dafault 
                            destinationForEmail = path + @"\Backup\Database_" + seq + ".rar";
                        }

                        startInfo.Arguments = "a -afrar " + destination + source;
                        try
                        {
                            // Call WaitForExit and then the using statement will close.
                            using (Process exeProcess = Process.Start(startInfo))
                            {
                                exeProcess.WaitForExit();
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }

                    // send backup database to admin via email
                    if (bacM.EmailAddr != "")
                    {
                       Email eml = new Email(bacM.EmailAddr, destinationForEmail, 0);
                       LbStatus.Text = eml.Status; 
                    }
                }
                if (temp1 != bacM.Date) bacM.Update(bacM.Auto, bacM.EmailAddr, bacM.Folder, bacM.Period);
            }
            
            
        }

        private void ShowTabpage(object sender, EventArgs e)
        {
            if (sender == PbBill) ShowTabPage(TabBill, tabControl1);
            if (sender == PbService) ShowTabPage(TabServices, tabControl1);
            if (sender == PbCustomer) ShowTabPage(TabCustomer, tabControl1);
            if (sender == PbPersonel)
            {
                 new Form2(REQUEST_TYPE.OPEN_TAB).ShowDialog();
                 if ((Privilege == USER_TYPE.ADMIN) || (Privilege == USER_TYPE.ENGINEER) || ( Privilege == USER_TYPE.MOD))  
                 {
                     ShowTabPage(TabPersonel, tabControl1);
                     Privilege = USER_TYPE.NONE;
                 }
            }
            if (sender == PbHistory) 
            {
                new Form2(REQUEST_TYPE.OPEN_TAB).ShowDialog();
                if ((Privilege == USER_TYPE.ADMIN) || (Privilege == USER_TYPE.ENGINEER) || (Privilege == USER_TYPE.MOD))
                {
                    ShowTabPage(TabHistory, tabControl1);
                    CbHis_Method.Text = "All";
                    CbHis_CustomerKey.Enabled = false;
                    Privilege = USER_TYPE.NONE;
                }
            }
           
        }

        private void Tmr_DateTime_Tick(object sender, EventArgs e)
        {
            LbDate.Text = DateTime.Now.ToString();
        }

        private void TabCustomer_ButtonClick(object sender, EventArgs e)
        {
            if( (sender == PbCM_Update) || (sender == PbCM_AddCustomer))
            {
                if( sender == PbCM_Update) CusM.UpdateDB();

                if (sender == PbCM_AddCustomer)
                {
                    CusM.AddNewCustomer(TxtCM_Id.Text, TxtCM_Name.Text, TxtCM_Phone.Text, CbCM_LV.Text);
                    TxtCM_Id.Clear();
                    TxtCM_Name.Clear();
                    TxtCM_Phone.Clear();
                    CbCM_LV.Text = "";
                }

                //-- customer update for Bill tab
                CbBill_CustomerName.AutoCompleteCustomSource = CusM.GetSourceForKey(CUSTOMER_SERACH_METHOD.NAME);
                TxtBill_CustomerID.AutoCompleteCustomSource = CusM.GetSourceForKey(CUSTOMER_SERACH_METHOD.ID);
                TxtBill_Phone.AutoCompleteCustomSource = CusM.GetSourceForKey(CUSTOMER_SERACH_METHOD.PHONE);
                TxtBill_LV.AutoCompleteCustomSource = CusM.GetSourceForKey(CUSTOMER_SERACH_METHOD.LV);
                CbBill_CustomerName.Items.Clear();
                for (int j = 0; j < CbBill_CustomerName.AutoCompleteCustomSource.Count; j++) CbBill_CustomerName.Items.Add(CbBill_CustomerName.AutoCompleteCustomSource[j]);
            }
            if (sender == PbCM_Search)
            {
                Customer_Search();
            }
            if (sender == CbCM_By)
            {
                TxtCM_Key.Clear();
                if (CbCM_By.Text == CbCM_By.Items[0].ToString()) // all
                    return;

                if (CbCM_By.Text == CbCM_By.Items[1].ToString()) // Id
                    TxtCM_Key.AutoCompleteCustomSource = CusM.GetSourceForKey(CUSTOMER_SERACH_METHOD.ID);

                if (CbCM_By.Text == CbCM_By.Items[2].ToString()) // Name
                    TxtCM_Key.AutoCompleteCustomSource = CusM.GetSourceForKey(CUSTOMER_SERACH_METHOD.NAME);

                if (CbCM_By.Text == CbCM_By.Items[3].ToString()) // Phone
                    TxtCM_Key.AutoCompleteCustomSource = CusM.GetSourceForKey(CUSTOMER_SERACH_METHOD.PHONE);
            }

        }

        private void Customer_Search()
        {
            string key = TxtCM_Key.Text;

            if (CbCM_By.Text == CbCM_By.Items[0].ToString()) // all
                customerTableBindingSource.DataSource = CusM.SearchBy(key, CUSTOMER_SERACH_METHOD.ALL);

            if (CbCM_By.Text == CbCM_By.Items[1].ToString()) // Id
                customerTableBindingSource.DataSource = CusM.SearchBy(key, CUSTOMER_SERACH_METHOD.ID);

            if (CbCM_By.Text == CbCM_By.Items[2].ToString()) // Name
                customerTableBindingSource.DataSource = CusM.SearchBy(key, CUSTOMER_SERACH_METHOD.NAME);

            if (CbCM_By.Text == CbCM_By.Items[3].ToString()) // Phone
                customerTableBindingSource.DataSource = CusM.SearchBy(key, CUSTOMER_SERACH_METHOD.PHONE);
        }

        private void TabService_ButonClick(object sender, EventArgs e)
        {
            if ((sender == PbSM_AddService) ||  (sender == PbSM_Update))
            {
                if (sender == PbSM_AddService)
                {
                    int temp = 0;
                    int.TryParse(TxtSM_Price.Text, out temp);

                    SerM.AddNewService(TxtSM_ID.Text, TxtSM_Name.Text, temp);
                }
                if (sender == PbSM_Update)
                {
                    RooM.UpdateDB();
                    SerM.UpdateDB();
                }

                //--service
                CbBill_ServiceName.AutoCompleteCustomSource = SerM.GetSourceForService(SERVICE_SOURCE_TYPE.NAME);
                TxtBill_ServiceID.AutoCompleteCustomSource = SerM.GetSourceForService(SERVICE_SOURCE_TYPE.ID);
                CbBill_ServiceName.Items.Clear();
                for (int j = 0; j < CbBill_ServiceName.AutoCompleteCustomSource.Count; j++) CbBill_ServiceName.Items.Add(CbBill_ServiceName.AutoCompleteCustomSource[j]);
            }
            if (sender == PbSM_UpdateCurrency)
            {              
                int temp = 0;
                int.TryParse(TxtSM_VND.Text, out temp);
                CurM.ExchangeRate = temp;  // update to DB also
            }
            if (sender == PbSM_UpdateVIPInfo)
            {
                int temp1 = 0;
                int temp2 = 0;

                int.TryParse(TxtSM_VIPRoomCharge.Text, out temp1);
                int.TryParse(TxtSM_VIPDiscount.Text, out temp2);
                               
                ProM.VIPRoomCharge = temp1;  // update to DB also
                ProM.VIPDiscount = temp2;   // update to DB also
            }
        }

        private void DataGridView_InputDataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Input value is invalid ! \r\n\r\n", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
        }

        private void TabPersonel_ButtonClick(object sender, EventArgs e)
        {
            if (sender == PbPM_Create)
            {
                int Id = 0;
                int.TryParse(TxtPM_ID.Text, out Id);

                PerM.AddNewStaff(Id, TxtPM_Name.Text, TxtPM_NationalID.Text, TxtPM_Phone.Text, TxtPM_Position.Text); // update DB also
                TxtPM_Name.Clear();
                TxtPM_NationalID.Clear();
                TxtPM_Phone.Clear();
                TxtPM_Position.Clear();
                TxtPM_ID.Clear();
            }
            if (sender == PbPM_Add)
            {
                // get ID form combo box
                int Id = 0;
                int.TryParse(CbPM_StaffID.Text, out Id);

                // check whether this ID is invalid or not
                string str = "";
                bool IsMember = false;
                for (int j = 0; j < CbPM_StaffID.Items.Count;j++ )
                {
                    str = CbPM_StaffID.GetItemText(CbPM_StaffID.Items[j]);
                    if (str == CbPM_StaffID.Text)
                    {
                        IsMember = true;
                        CbPM_StaffID.SelectedItem = j;
                        break;
                    }
                }

                // if ID is existed in database, process it
                // otherwise, return error information
                if (IsMember == false)
                {
                    MessageBox.Show("This ID is not existed", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    return;
                }
                else
                {
                    var result = MessageBox.Show("Do you want to add " + NuPM_Point.Value.ToString() + " point(s) for this staff : \r\nID : " + Id.ToString()+"\r\nName : " + PerM.GetNameOfStaff(Id), "CONFIRM", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                    if (result == System.Windows.Forms.DialogResult.Yes)
                    {
                        PerM.AddPointForStaff(Id,(int) NuPM_Point.Value);       // update DB also
                    }                   
                }
            }
            if (sender == PbPM_ResetMonthAcc)
            {
                var m = MessageBox.Show("Do you really want to reset ?", "CONFIRM", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if(m == System.Windows.Forms.DialogResult.Yes)
                     PerM.ResetMonthAcc();   // update DB also
            }
            if (sender == PbPM_ResetYearAcc)
            {
                var m = MessageBox.Show("Do you really want to reset ?", "CONFIRM", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (m == System.Windows.Forms.DialogResult.Yes)
                PerM.ResetYearAcc();    // update DB also
            }
            if (sender == PbPM_Update)
            {
                PerM.UpdateDB();
            }
        }        

        private void SearchTime_Change(object sender, EventArgs e)
        {
            
            DatabaseDataSet.BillMainTableDataTable tb = new DatabaseDataSet.BillMainTableDataTable();
            if (sender == LbHis_All)                
                SearchTime = TIME_CONSTRAIN.ALL;
            else if (sender == LbHis_Today)                
                SearchTime = TIME_CONSTRAIN.TODAY;
            else if (sender == LbHis_Yesterday)                
                SearchTime = TIME_CONSTRAIN.YESTERDAY;
            else if (sender == LbHis_Last7Days)                
                SearchTime = TIME_CONSTRAIN.LAST7DAY;
            else if (sender == LbHis_ThisMonth)                
                SearchTime = TIME_CONSTRAIN.THISMONTH;
            else                
                SearchTime = TIME_CONSTRAIN.TODAY;
            HistorySearch();
        }

        private void CbHis_Method_SelectedIndexChanged(object sender, EventArgs e)
        {
            int count;
            int index;
            string temp;
            string Method = CbHis_Method.Text;

            CbHis_CustomerKey.Items.Clear();
            CbHis_CustomerKey.Text = "";
            CbHis_CustomerKey.Enabled = true;
            GbHis_Time.Visible = true;
            if (Method == "All")
            {
                SearchMethod = SEARCH_METHOD.ALL;
                CbHis_CustomerKey.Enabled = false;
            }
            else if (Method == "Bill No.")
            {
                SearchMethod = SEARCH_METHOD.BILL_NO;                
                history.LoadDB();
                count = history.BillMainDataTableRowsCount;
                for (index = 0; index < count; index++)
                {                    
                    temp = history.BillNumber(index);
                    CbHis_CustomerKey.Items.Add(temp);
                }
                GbHis_Time.Visible = false;
            }
            else if (Method == "Customer Name")
            {
                count = CusM.Count;
                SearchMethod = SEARCH_METHOD.CUSTOMER_NAME;
                for (index = 0; index < count; index++)
                {
                    temp = databaseDataSet.CustomerTable[index]["Name"].ToString();
                    CbHis_CustomerKey.Items.Add(temp);
                }
            }
            else if (Method == "Cashier")
            {
                SearchMethod = SEARCH_METHOD.CASHIER;
            }

            else if (Method == "Room")
            {                
                SearchMethod = SEARCH_METHOD.ROOM;
                count = databaseDataSet.RoomTable.Rows.Count;
                for (index = 0; index < count; index++)
                {
                    temp = databaseDataSet.RoomTable.Rows[index]["Name"].ToString();
                    CbHis_CustomerKey.Items.Add(temp);
                }
            }
            else // All
            {
                SearchMethod = SEARCH_METHOD.ALL;
                CbHis_CustomerKey.Enabled = false;
            }          
        }

        private void TabBill_ButtonClick(object sender, EventArgs e)
        {
            if (sender == TxtBill_BillNo)
            {
                BilM.Current_BillNumber = TxtBill_BillNo.Text;
            }
           
            if (sender == PbBM_Add)
            {
                int Price = 0;
                int Discount = 0;
                string Notes = "";

                // convert from string to int
                string s = RemoveComma(TxtBill_Price.Text);
                int.TryParse(s, out Price);

                s = RemoveComma(TxtBill_Discount.Text);
                int.TryParse(s, out Discount);
                if (ChkPercent.Checked)
                {
                    if (Discount > 100) Discount = 100;
                }

                // add row to DataTable
                bool bAddSuccess = false;
                bAddSuccess = BilM.AddNewRowToBillDtails(CbBill_ServiceName.Text,TxtBill_ServiceID.Text, (int)NuBill_Quantity.Value, Price, Discount, ChkPercent.Checked,CbBill_Room.Text);

                if (bAddSuccess)
                {
                    // check VIP room and VIP customer
                    int roomCharge = RooM.RoomCharge(CbBill_Room.Text);
                    string Customer_LV = TxtBill_LV.Text.ToUpper();
                    if ((roomCharge > 0) && (Customer_LV != "VIP")) // vip room and not VIP customer --> charge more money
                    {
                       bAddSuccess =  BilM.AddNewRowToBillDtails("VIPRoom+" + roomCharge.ToString() + "%", "VIPR", (int)NuBill_Quantity.Value, Price * roomCharge / 100, 0, false, CbBill_Room.Text);
                    }
                    if ((roomCharge == 0) && (Customer_LV == "VIP"))
                    {
                       bAddSuccess = BilM.AddNewRowToBillDtails("VIPDiscount-" + ProM.VIPDiscount + "%", "VIPD", (int)NuBill_Quantity.Value,0 , Price * ProM.VIPDiscount / 100, false, CbBill_Room.Text);
                    }

                    if (bAddSuccess)
                    {
                        // calculate total and return
                        txtBill_Total.Text = BilM.GetTotal().ToString("0,0");
                        TxtBill_Return.Text = BilM.GetReturn(CurM.ExchangeRate).ToString("0,0");
                    }
                    else  // full row in bill, we need to delete last row
                    {
                        BilM.DeleteLastRow();
                    }

                    // clear text
                    CbBill_ServiceName.Text = "";
                    TxtBill_ServiceID.Clear();
                    TxtBill_Price.Clear();
                    TxtBill_Discount.Clear();
                    NuBill_Quantity.Value = 1;
                }
            }

            if (sender == PbBM_New)
            {
                ClearTextInTabBill();
                BilM.ClearDataTableBill();
                BilM.ServiceNameList.Clear();
                TxtBill_BillNo.Text = BilM.Create_New_BillNo();

                // update status
                LbStatus.Text = "New Bill";
            }
            if ((sender == PbPrint) || (sender == PbBM_Save))
            {
                List<InvoiceData> DataList  = new List<InvoiceData>(_PrintArray);
                if (sender == PbPrint)
                {
                    // Warning
                    var m = MessageBox.Show("Do you want to print this bill", "INFO", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                    if (m == System.Windows.Forms.DialogResult.No) return;
                
                    // Update status
                    LbStatus.Text = "Printing...";

                    // insert data to Main table
                    BilM.Cashier = TxtBill_Cashier.Text;
                    BilM.Room = CbBill_Room.Text;
                    BilM.Customer = CbBill_CustomerName.Text;
                    BilM.CustomerID = TxtBill_CustomerID.Text;
                    BilM.StaffNo = TxtBill_Staff.Text;

                    // Print : take information from MainTable and DetailsTable
                    InitPrintArray();
                    FillPrintHeadData();
                    FillPrintBodyData();
                    FillPrintSummaryData();
                    DataList = new List<InvoiceData>(_PrintArray);
                    PrintReport pr = new PrintReport(DataList);
                    pr.PrintInvoice();

                    // enable Save button
                    PbBM_Save.Enabled = true;
                    PbBM_Add.Enabled = false;
                    PbBM_New.Enabled = false;
                    PbPrint.Enabled = false;
                }

                if (sender == PbBM_Save)
                {
                    // add point for customer if he/she is our member
                    if (CusM.AddPointForCustomer(BilM.Total, BilM.CustomerID))
                        MessageBox.Show(BilM.Customer + " has been added " + BilM.Total.ToString("0,0") + " VND into his/her account");

                    // Update To DB: both main and details
                    bool bError;
                    bError = BilM.InsertNewBillToDB();
                    if (bError)
                    {
                        MessageBox.Show("Error ! No service in this bill", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                        return;
                    }

                    // confirm for cashier
                    // MessageBox.Show("Data has been stored", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    LbStatus.Text = "Data has been stored";
                    
                    // Email

                    BillTemplate billTemplate = new BillTemplate(DataList, TxtBill_BillNo.Text, BilM.Cashier);
                    EmailManagement em = new EmailManagement();
                    LbStatus.Text =  em.SendMailWithNewBill(billTemplate);  

                    // disable Save button
                    PbBM_Save.Enabled = false;
                    PbPrint.Enabled = true;
                    PbBM_Add.Enabled = true;
                    PbBM_New.Enabled = true;
                }
            }
            
            if((sender == CbBill_CustomerName) || (sender == TxtBill_CustomerID) || (sender == TxtBill_Phone))
            {
                int j = -1;
                if (sender == CbBill_CustomerName) j = CbBill_CustomerName.AutoCompleteCustomSource.IndexOf(CbBill_CustomerName.Text);
                if (sender == TxtBill_CustomerID) j = TxtBill_CustomerID.AutoCompleteCustomSource.IndexOf(TxtBill_CustomerID.Text);
                if (sender == TxtBill_Phone) j = TxtBill_Phone.AutoCompleteCustomSource.IndexOf(TxtBill_Phone.Text);
                
                if (j > -1)
                {
                    CbBill_CustomerName.Text = CbBill_CustomerName.AutoCompleteCustomSource[j];
                    TxtBill_CustomerID.Text = TxtBill_CustomerID.AutoCompleteCustomSource[j];
                    TxtBill_Phone.Text = TxtBill_Phone.AutoCompleteCustomSource[j];
                    TxtBill_LV.Text = TxtBill_LV.AutoCompleteCustomSource[j];
                }
            }

            if ((sender == CbBill_ServiceName) || (sender == TxtBill_ServiceID))
            {
                int j = -1;
                if (sender == CbBill_ServiceName) j = CbBill_ServiceName.AutoCompleteCustomSource.IndexOf(CbBill_ServiceName.Text);
                if (sender == TxtBill_ServiceID) j = TxtBill_ServiceID.AutoCompleteCustomSource.IndexOf(TxtBill_ServiceID.Text);

                if (j > -1)
                {
                    CbBill_ServiceName.Text = CbBill_ServiceName.AutoCompleteCustomSource[j];
                    TxtBill_ServiceID.Text = TxtBill_ServiceID.AutoCompleteCustomSource[j];
                    TxtBill_Price.Text = SerM.PriceList[j];
                    TxtBill_Discount.Text = SerM.DiscountList[j];
                    ChkPercent.Checked = SerM.PercentList[j];
                }
            }
         

        }

        private void TabBill_TextValidated(object sender, EventArgs e)
        {
            if (sender == TxtBill_KVND)
            {
                int.TryParse(RemoveComma(TxtBill_KVND.Text), out BilM.VND);
            }
            if (sender == TxtBill_USD)
            {
                int.TryParse(RemoveComma(TxtBill_USD.Text), out BilM.USD);
            }
            if (sender == TxtBill_Card)
            {
                int.TryParse(RemoveComma(TxtBill_Card.Text), out BilM.Card);
            }
            if (sender == TxtBill_TotalDiscount)
            {
                if (TxtBill_TotalDiscount.Text == "") return;
                var m = MessageBox.Show("Do you want to apply Total Discount", "INFO", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (m == System.Windows.Forms.DialogResult.Yes)
                {
                    int temp = 0;
                    int.TryParse(TxtBill_TotalDiscount.Text, out temp);
                    BilM.ApplyTotalDiscount(temp);

                    txtBill_Total.Text = BilM.GetTotal().ToString("0,0");
                }
                else TxtBill_TotalDiscount.Text = "";
            }
            if (sender == TxtBill_Voucher)
            {
                int.TryParse(RemoveComma(TxtBill_Voucher.Text), out BilM.Voucher);
                txtBill_Total.Text = BilM.GetTotal().ToString("0,0");
            }
            if (sender == TxtBill_Tips)
            {
                int.TryParse(RemoveComma(TxtBill_Tips.Text), out BilM.Tips);

                // calculate total and return
                txtBill_Total.Text = BilM.GetTotal().ToString("0,0");
            }

            TxtBill_Return.Text = BilM.GetReturn(CurM.ExchangeRate).ToString("0,0");

            if ((sender == TxtBill_Price) || (sender == TxtBill_Discount) || (sender == TxtBill_KVND) || (sender == TxtBill_USD) || (sender == TxtBill_Card) || (sender == TxtBill_Voucher) || (sender == TxtBill_Tips))
            {
                int temp = 0;
                TextBox t = (TextBox)sender;

                int.TryParse(RemoveComma(t.Text), out temp);
                t.Text = temp.ToString("0,0");
                if (t.Text == "00") t.Text = "0";
                return; // need to return
            }
            
        }

        private void TabBill_Dtg_RowDeteled(object sender, DataGridViewRowEventArgs e)
        {
            // calculate total and return
            txtBill_Total.Text = BilM.GetTotal().ToString("0,0");
            TxtBill_Return.Text = BilM.GetReturn(CurM.ExchangeRate).ToString("0,0");
        }
        private void DtgBill_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            // delete item in ServiceNameList in BilM
            try
            {
                BilM.ServiceNameList.RemoveAt(e.Row.Index);
            }
            catch (Exception)
            { }
        }

        private void ClearTextInTabBill()
        {
            CbBill_CustomerName.Text = "";
            TxtBill_CustomerID.Text = "";
            TxtBill_Phone.Text = "";
            TxtBill_LV.Text = "";

            TxtBill_ServiceID.Text = "";
            CbBill_ServiceName.Text = "";
            TxtBill_Price.Text = "";
            NuBill_Quantity.Value = 1;
            TxtBill_Discount.Text = "";
            ChkPercent.Checked = false;

            TxtBill_KVND.Text = "0";
            TxtBill_USD.Text = "0";
            TxtBill_Card.Text = "0";

            TxtBill_TotalDiscount.Text = "";
            TxtBill_Voucher.Text = "";
            TxtBill_Return.Text = "";

            txtBill_Total.Text = "0";
            TxtBill_Return.Text = "0";

            TxtBill_TotalDiscount.Text = "";
            TxtBill_Voucher.Text = "0";
            TxtBill_Tips.Text = "0";

            TxtBill_BillNo.Text = "";
            TxtBill_Staff.Text = "";
            LbStatus.Text = "New Bill";

        }

        private string RemoveComma(string s)
        {
            int index = 0;
            do
            {
                index = s.IndexOf(",");
                if(index > -1) s = s.Substring(0, index) + s.Substring(index + 1);              
            }
            while (index > -1);
            return s;
        }

        private void HistorySearch()
        {
            SearchKey = CbHis_CustomerKey.Text;
            billMainTableBindingSource.DataSource = history.Search(SearchMethod, SearchTime, SearchKey);
        }

        private void Search_Event(object sender, EventArgs e)
        {
            HistorySearch();
        }

        private void KeyUp_EventHandle(object sender, KeyEventArgs e)
        {
            if (sender == CbHis_CustomerKey)
            {
                if (e.KeyValue == 13)
                    HistorySearch();
            }
            if (sender == TxtCM_Key)
            {
                if (e.KeyValue == 13)
                    Customer_Search();
            }

        }

        private void PbHis_ViewDetails_Click(object sender, EventArgs e)
        {
            FormBillDetails formBillDetails = new FormBillDetails(history);
            formBillDetails.BillNumber = CbHis_CustomerKey.Text;            
            formBillDetails.ShowDialog();
        }

        private void Menu_Click(object sender, EventArgs e)
        {
            if(sender == UserManagement)
            {
                Form2.VIPM = VIPM;
                new Form2(REQUEST_TYPE.CONFIG).ShowDialog();
            }
            if (sender == Menu_Backup)
            {
                new Form2(REQUEST_TYPE.BACKUP).ShowDialog();
            }
            if (sender == Menu_Exit)
                Close();
            if (sender == Menu_About)
                MessageBox.Show("Spa Management V1.0 - HD Solutions\r\n\r\nEmail : HDSolutions.VH@gmail.com\r\n\r\nPhone : 0973.888.427", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            if (sender == Menu_How2Use)
            {
                try
                {
                    Process.Start(Application.StartupPath + "\\Manual.pdf");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            if (sender == Menu_ReportDay)
            {
                string path = Path.Combine(Application.StartupPath, "Excel Templates\\Report.xls");
                string exSheetName = DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString();
                // string.Format("{0:M_d_yyyy}", exSheetName);
                exp2Excel.ExportFromDatabse(history.Search(SEARCH_METHOD.ALL, TIME_CONSTRAIN.TODAY, null), path, exSheetName); 
            }
            if (sender == Menu_ReportMoth)
            {
                string path = Path.Combine(Application.StartupPath, "Excel Templates\\Report.xls");
                string exSheetName = DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString();                
                exp2Excel.ExportFromDatabse(history.Search(SEARCH_METHOD.ALL, TIME_CONSTRAIN.THISMONTH, null), path, exSheetName); 
            }
            if (sender == Menu_CurrencyConverter)
                try
                {
                    System.Diagnostics.Process.Start("calc");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
        }                

      

        private void dateTimePickerTo_Enter(object sender, EventArgs e)
        {
            DateTime dtMin = dateTimePickerFrom.Value;
            DateTime dtMax = dateTimePickerTo.Value;
            SearchTime = TIME_CONSTRAIN.PERIOD;
            history.MaxDate = new DateTime(dtMax.Year, dtMax.Month, dtMax.Day, 23, 59, 59);
            history.MinDate = new DateTime(dtMin.Year, dtMin.Month, dtMin.Day, 0, 0, 0);
            
            string.Format("{0:M/d/yyyy}", history.MaxDate);
            string.Format("{0:M/d/yyyy}", history.MinDate);
            HistorySearch();
        }

        private void ExportToExcel(object sender, EventArgs e)
        {           
            string path = Path.Combine(Application.StartupPath, "Excel Templates\\Blank.xls");
            if (sender == PbCM_Export2Excel) exp2Excel.ExportFromDatgridView(GridView_CV, path, "Customer");
            if (sender == PbPM_Export2Excel) exp2Excel.ExportFromDatgridView(DtgPersonel, path, "Personel");
            if (sender == PbSM_Export2Excel) exp2Excel.ExportFromDatgridView(DtgService, path, "Service");
            if (sender == PbHis_Excel)
            {
                path = Path.Combine(Application.StartupPath, "Excel Templates\\Report.xls");
                exp2Excel.ExportFromDatabse(history.Search(SearchMethod, SearchTime, SearchKey), path, "Report"); 
            }
        }

        private void InitPrintArray()
        {
            _PrintArray = new InvoiceData[]
            {            
                new InvoiceData() {index= 0, ID = GUEST_BILL.DATE, X = 640, Y = 0, Data = null},
                new InvoiceData() {index= 1, ID = GUEST_BILL.NUMBER, X = 640, Y = 23, Data = null},
                new InvoiceData() {index= 2, ID = GUEST_BILL.STAFF_NUMBER, X = 640, Y = 45, Data = null},
                new InvoiceData() {index= 3, ID = GUEST_BILL.ROOM , X = 640, Y = 66, Data = null},

                new InvoiceData() {index= 4, ID = GUEST_BILL.CUSTOMER, X = 140, Y = 90, Data = null}, // Customer's Name

                new InvoiceData() {index= 5, ID = GUEST_BILL.NO_1, X = 14, Y = 158, Data = null},
                new InvoiceData() {index= 6, ID = GUEST_BILL.DESC_1, X = 40, Y = 158, Data = null},
                new InvoiceData() {index= 7, ID = GUEST_BILL.CODE_1, X = 180, Y = 158, Data = null},
                new InvoiceData() {index= 8, ID = GUEST_BILL.QTY_1, X = 224, Y = 158, Data = null},
                new InvoiceData() {index= 9, ID = GUEST_BILL.UNIT_PRICE_1, X = 280, Y = 158, Data = null},
                new InvoiceData() {index= 10, ID = GUEST_BILL.USD_1, X = 380, Y = 158, Data = null},
                new InvoiceData() {index= 11, ID = GUEST_BILL.VND_1, X = 432, Y = 158, Data = null},
                new InvoiceData() {index= 12, ID = GUEST_BILL.DISCOUNT_1, X = 538, Y = 158, Data = null},
                new InvoiceData() {index= 13, ID = GUEST_BILL.NOTE_1, X = 616, Y = 158, Data = null},

                new InvoiceData() {index= 14, ID = GUEST_BILL.NO_2, X = 14, Y = 186, Data = null},
                new InvoiceData() {index= 15, ID = GUEST_BILL.DESC_2, X = 40, Y = 186, Data = null},
                new InvoiceData() {index= 16, ID = GUEST_BILL.CODE_2, X = 180, Y = 186, Data = null},
                new InvoiceData() {index= 17, ID = GUEST_BILL.QTY_2, X = 224, Y = 186, Data = null},
                new InvoiceData() {index= 18, ID = GUEST_BILL.UNIT_PRICE_2, X = 280, Y = 186, Data = null},
                new InvoiceData() {index= 29, ID = GUEST_BILL.USD_2, X = 380, Y = 186, Data = null},
                new InvoiceData() {index= 20, ID = GUEST_BILL.VND_2, X = 432, Y = 186, Data = null},
                new InvoiceData() {index= 21, ID = GUEST_BILL.DISCOUNT_2, X = 538, Y = 186, Data = null},
                new InvoiceData() {index= 22, ID = GUEST_BILL.NOTE_2 , X = 616, Y = 186, Data = null},

                new InvoiceData() {index= 23, ID = GUEST_BILL.NO_3, X = 14, Y = 214, Data = null},
                new InvoiceData() {index= 24, ID = GUEST_BILL.DESC_3, X = 40, Y = 214, Data = null},
                new InvoiceData() {index= 25, ID = GUEST_BILL.CODE_3 , X = 180, Y = 214, Data = null},
                new InvoiceData() {index= 26, ID = GUEST_BILL.QTY_3 , X = 224, Y = 214, Data = null},
                new InvoiceData() {index= 27, ID = GUEST_BILL.UNIT_PRICE_3, X = 280, Y = 214, Data = null},
                new InvoiceData() {index= 28, ID = GUEST_BILL.USD_3, X = 380, Y = 214, Data = null},
                new InvoiceData() {index= 29, ID = GUEST_BILL.VND_3, X = 432, Y = 214, Data = null},
                new InvoiceData() {index= 30, ID = GUEST_BILL.DISCOUNT_3, X = 538, Y = 214, Data = null},
                new InvoiceData() {index= 31, ID = GUEST_BILL.NOTE_3 , X = 616, Y = 214, Data = null},

                new InvoiceData() {index= 32, ID = GUEST_BILL.NO_4, X = 14, Y = 242, Data = null},
                new InvoiceData() {index= 33, ID = GUEST_BILL.DESC_4, X = 40, Y = 242, Data = null},
                new InvoiceData() {index= 34, ID = GUEST_BILL.CODE_4, X = 180, Y = 242, Data = null},
                new InvoiceData() {index= 35, ID = GUEST_BILL.QTY_4, X = 224, Y = 242, Data = null},
                new InvoiceData() {index= 36,ID = GUEST_BILL.UNIT_PRICE_4, X = 280, Y = 242, Data = null},
                new InvoiceData() {index= 37, ID = GUEST_BILL.USD_4, X = 380, Y = 242, Data = null},
                new InvoiceData() {index= 38, ID = GUEST_BILL.VND_4, X = 432, Y = 242, Data = null},
                new InvoiceData() {index= 39, ID = GUEST_BILL.DISCOUNT_4, X = 538, Y = 242, Data = null},
                new InvoiceData() {index= 40, ID = GUEST_BILL.NOTE_4, X = 616, Y = 242, Data = null},

                new InvoiceData() {index= 41, ID = GUEST_BILL.NO_5, X = 14, Y = 269, Data = null},
                new InvoiceData() {index= 42, ID = GUEST_BILL.DESC_5, X = 40, Y = 269, Data = null},
                new InvoiceData() {index= 43, ID = GUEST_BILL.CODE_5, X = 180, Y = 269, Data = null},
                new InvoiceData() {index= 44, ID = GUEST_BILL.QTY_5, X = 224, Y = 269, Data = null},
                new InvoiceData() {index= 45, ID = GUEST_BILL.UNIT_PRICE_5, X = 280, Y = 269, Data = null},
                new InvoiceData() {index= 46, ID = GUEST_BILL.USD_5, X = 380, Y = 269, Data = null},
                new InvoiceData() {index= 47, ID = GUEST_BILL.VND_5, X = 432, Y = 269, Data = null},
                new InvoiceData() {index= 48, ID = GUEST_BILL.DISCOUNT_5, X = 538, Y = 269, Data = null},
                new InvoiceData() {index= 49, ID = GUEST_BILL.NOTE_5, X = 616, Y = 269, Data = null},

                new InvoiceData() {index= 50, ID = GUEST_BILL.NO_6, X = 14, Y = 297, Data = null},
                new InvoiceData() {index= 51, ID = GUEST_BILL.DESC_6, X = 40, Y = 297, Data = null},
                new InvoiceData() {index= 52, ID = GUEST_BILL.CODE_6, X = 180, Y = 297, Data = null},
                new InvoiceData() {index= 53, ID = GUEST_BILL.QTY_6, X = 224, Y = 297, Data = null},
                new InvoiceData() {index= 54, ID = GUEST_BILL.UNIT_PRICE_6, X = 280, Y = 297, Data = null},
                new InvoiceData() {index= 55, ID = GUEST_BILL.USD_6, X = 380, Y = 297, Data = null},
                new InvoiceData() {index= 56, ID = GUEST_BILL.VND_6, X = 432, Y = 297, Data = null},
                new InvoiceData() {index= 57, ID = GUEST_BILL.DISCOUNT_6, X = 538, Y = 297, Data = null},
                new InvoiceData() {index= 58, ID = GUEST_BILL.NOTE_6, X = 616, Y = 297, Data = null},

                new InvoiceData() {index= 59, ID = GUEST_BILL.TOTAL, X = 432, Y = 324, Data = null},
                new InvoiceData() {index= 60, ID = GUEST_BILL.TOTAL_EX, X = 550, Y = 324, Data = null},  // THIS CELL HAS NO FUNCTIONALITY IN THE INVOICE EXCEPT FOR EXTRA PURPOSES
                new InvoiceData() {index= 61, ID = GUEST_BILL.DISCOUNT_TOTAL, X = 432, Y = 350, Data = null},
                new InvoiceData() {index= 62, ID = GUEST_BILL.DISCOUNT_TOTAL_EX, X = 550, Y = 350, Data = null}, // THIS CELL HAS NO FUNCTIONALITY IN THE INVOICE EXCEPT FOR EXTRA PURPOSES
                new InvoiceData() {index= 63, ID = GUEST_BILL.EXCHANGE_RATE, X = 140, Y = 378, Data = null},
                new InvoiceData() {index= 64, ID = GUEST_BILL.VOUCHER, X = 480, Y = 378, Data = null},
                new InvoiceData() {index= 65, ID = GUEST_BILL.TIPS, X = 580, Y = 378, Data = "Tips: "},
                new InvoiceData() {index= 66, ID = GUEST_BILL.TOTAL_FINAL, X = 480, Y = 399, Data = null},
                new InvoiceData() {index= 67, ID = GUEST_BILL.EQUIVALENT, X = 480, Y = 421, Data = null},                
            };
        }

        private void FillPrintHeadData()
        {
            _PrintArray[0].Data = DateTime.Now.Month + "/" + DateTime.Now.Day + "/" + DateTime.Now.Year;
            _PrintArray[1].Data = null;
            _PrintArray[2].Data = BilM.StaffNo; //BilM.Cashier;
            _PrintArray[3].Data = BilM.Room;
            _PrintArray[4].Data = BilM.Customer;
        }


        private void FillPrintBodyData()
        {
            string[][] BillBodyData = new string[6][];
            int maxLength = BilM.MaxLengthOfServiceNameColumm;
            string description = "";
            int Count = 1; // Sequence

           
            for (int j = 0; j < 6; j++) BillBodyData[j] = new string[9];

            // fill rows sequently 
            int NumberOfLoop = BilM.ServiceNameList.Count;
            int step = 0;
            for (int i = 0; i < NumberOfLoop; i++)
            {
                description = BilM.ServiceNameList[i+step]; // Service Name

               
                BillBodyData[i][0] = (Count++).ToString();// Sequence

                BillBodyData[i][2] = BilM._DataTable_Details[i+step].ServiceID; //Service Code
                BillBodyData[i][3] = BilM._DataTable_Details[i+step].Quantity.ToString();// Quantity

                int UnitPriceTemp = BilM._DataTable_Details[i + step].PricePerUnit;
                if (UnitPriceTemp == 0) BillBodyData[i][4] = "0";
                else BillBodyData[i][4] = UnitPriceTemp.ToString("0,0");            // Unit Price

                BillBodyData[i][5] = null; // USD

                int VNDTemp = BilM._DataTable_Details[i + step].PricePerUnit * BilM._DataTable_Details[i + step].Quantity;
                if (VNDTemp == 0) BillBodyData[i][6] = "0";
                else BillBodyData[i][6] = VNDTemp.ToString("0,0"); // VND

                int DiscountTemp = - BilM._DataTable_Details[i+step].Price + BilM._DataTable_Details[i+step].PricePerUnit * BilM._DataTable_Details[i+step].Quantity;
                if (DiscountTemp == 0) BillBodyData[i][7] = "0";
                else BillBodyData[i][7] = DiscountTemp.ToString("0,0"); // Discount
               
                BillBodyData[i][8] = BilM._DataTable_Details[i+step].Notes; // Notes

                if (description.Length <= maxLength) BillBodyData[i][1] = description;
                else
                {
                    // cut description into two strings, 1st string's length = maxLength
                    string s1;
                    string s2; ;
                    s1 = description.Substring(0, maxLength)+"-";
                    s2 = "-" + description.Substring(maxLength);
        
                    BillBodyData[i++][1] = s1;
                    BillBodyData[i][1] = s2;
                    NumberOfLoop++;
                    step--;
                }                              
            }
            for (int i = 5; i <= 58; )
                for (int j = 0; j < 6; j++)
                    for (int k = 0; k < 9; k++)                    
                        _PrintArray[i++].Data = BillBodyData[j][k];                                            
        }

        private void FillPrintSummaryData()
        {
            _PrintArray[59].Data = BilM.GetRawTotalForPrintingBill().ToString("0,0"); //TOTAL
            _PrintArray[60].Data = null; //TOTAL_EX COLUMN

            int discountTotal = BilM.GetTotalDiscountForPrintingBill();
            if (discountTotal == 0) _PrintArray[61].Data = "0";
            else _PrintArray[61].Data = discountTotal.ToString("0,0"); //DISCOUNT TOTAL

            _PrintArray[62].Data = null; //DIACOUNT TOTAL EX COLUMN
            _PrintArray[63].Data = CurM.ExchangeRate.ToString("0,0");

            int voucherTemp = BilM.Voucher;
            if (voucherTemp == 0) _PrintArray[64].Data = "0";
            else _PrintArray[64].Data = voucherTemp.ToString("0,0");

            if (BilM.Tips == 0) _PrintArray[65].Data += "0";
            else _PrintArray[65].Data += BilM.Tips.ToString("0,0");

            if (BilM.GetTotal() == 0)
            {
                _PrintArray[66].Data = "0";
                _PrintArray[67].Data = "0";
            }
            else
            {
                _PrintArray[66].Data = BilM.GetTotal().ToString("0,0");  //FINAL TOTAL
                _PrintArray[67].Data = ((double)BilM.GetTotal() / CurM.ExchangeRate).ToString("0,0.0") + " USD"; //EQUIVALENT
            }
        }


    }
}
